package com.marion.codestandard.common.constraints;

import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author Marion
 * @date 2022/5/13 15:43
 */
public class PhoneValidator implements ConstraintValidator<Phone, String> {
    /**
     * Initializes the validator in preparation for
     * {@link #isValid(Object, ConstraintValidatorContext)} calls.
     * The constraint annotation for a given constraint declaration
     * is passed.
     * <p>
     * This method is guaranteed to be called before any use of this instance for
     * validation.
     * <p>
     * The default implementation is a no-op.
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(Phone constraintAnnotation) {

    }

    /**
     * Implements the validation logic.
     * The state of {@code value} must not be altered.
     * <p>
     * This method can be accessed concurrently, thread-safety must be ensured
     * by the implementation.
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (!StringUtils.isEmpty(value)) {
            return isPhone(value);
        }
        return false;
    }

    private boolean isPhone(String phone) {
        return phone.matches("^((13[0-9])|(15[^4,\\D])|(18[0,3-9]))\\d{8}$");
    }

}
